//
//  PaymentListViewController.m
//  HuLaQuan
//
//  Created by hok on 1/16/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "PaymentListViewController.h"

//cells
#import "PaymentListCell.h"

//logic model
#import "GetTradeListEngine.h"

//#import <KVNProgress/KVNProgress.h>

//Jump To
#import "PaymentListInfoViewController.h"

//refresh animation
#import "JHRefresh.h"

@interface PaymentListViewController ()

@property (strong, nonatomic) NSMutableArray *paymentList; //of keys;

@property (strong, nonatomic) NSIndexPath *selectIndexPath;

@property(nonatomic,strong)GetTradeListEngine *listEngine;

@property (nonatomic) NSInteger loadIndex;

@property (nonatomic) BOOL isPull; //上拉还是下拉
@end

static NSString * const PaymentListCellIdentifier = @"PaymentListCell";

@implementation PaymentListViewController

- (GetTradeListEngine *)listEngine
{
    if (!_listEngine) {
        _listEngine = [[GetTradeListEngine alloc] init];
    }
    return _listEngine;
}

- (NSMutableArray *)paymentList
{
    if (!_paymentList) {
        _paymentList = [[NSMutableArray alloc] init];
    }
    return _paymentList;
}

#pragma mark -  Life Cycle

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getTradeListFinish:) name:@"GetTradeListFinish" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetTradeListFinish" object:nil];
    
}

/*
 上拉加载，下拉刷新
 */
- (void)addRefreshView
{
    __weak typeof (self) wealSelf = self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //        _start = 1;
        [wealSelf refreshTableView];
    }];
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //        wealSelf.start++;
        [wealSelf refreshMoreData];
        
    }];
    
}
- (void)refreshTableView
{
    self.isPull = YES;
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.listEngine getTradeListWithIndex:0];
}
- (void)refreshMoreData
{
    
    //NSLog(@"记录 %d",[self.incomeRecords count]);
    if ([self.paymentList count] && [self.paymentList count] % 20 == 0) {
        self.isPull = NO;
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.listEngine getTradeListWithIndex:[self.paymentList count]/20];
    }else{
        [self.view makeToast:@"已经没有更早的记录了"];
        [self.tableView footerEndRefreshing];
    }
}
#pragma mark -  Call Back
- (void)getTradeListFinish:(NSNotification*) notification
{
    //
    //   dispatch_async(dispatch_get_main_queue(), ^{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        NSLog(@"%@",messageDic[@"result"][@"list"][@"trade"]);
        if ([messageDic[@"result"][@"list"][@"trade"] isKindOfClass:[NSArray class]]) {
            
            
            if (self.isPull) {
                [self.paymentList removeAllObjects];
            }

            [self.paymentList addObjectsFromArray:messageDic[@"result"][@"list"][@"trade"] ];
            
            [self.tableView reloadData];
        }
        
       
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
    if (self.isPull) {
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }else{
        [self.tableView footerEndRefreshing];
    }
    
    //  });
    
}

- (void)setupUI
{
    
    [self setupFooterForTableView];
    
    [self setupNavBackButton];
    
    [self.tableView registerNib:[PaymentListCell nib] forCellReuseIdentifier:PaymentListCellIdentifier];
    
    self.title = @"账单";
    
    [self addRefreshView];
    
    [self refreshTableView];
    
    
}


#pragma mark -  UITableViewDataSource



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kNormalCellHeight;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.paymentList.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return kUserCenterSectionHeaderHeight;
    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    PaymentListCell *cell = [tableView dequeueReusableCellWithIdentifier:PaymentListCellIdentifier
                                                            forIndexPath:indexPath];
    // cell.noticeLabel.text = @"请添加新账户";
    
    // cell.titleLabel.text = self.paymentList[indexPath.row][@"title"];
    cell.detailLabel.text = self.paymentList[indexPath.row][@"resName"];
    cell.timeLabel.text = [self.paymentList[indexPath.row][@"txnDate"] substringToIndex:10];
    cell.titleLabel.text = ServerMoneyFloatToShow(self.paymentList[indexPath.row][@"txnAmt"]) ;
    
    return cell;
    
    
    
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.selectIndexPath = indexPath;
    [self performSegueWithIdentifier:@"ShowPaymentListInfoViewController" sender:self];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"ShowPaymentListInfoViewController"]) {
        PaymentListInfoViewController *controller = (PaymentListInfoViewController *)[segue destinationViewController];
        controller.tradeID = self.paymentList[self.selectIndexPath.row][@"tradeId"];
    }
}


@end
